package com.fh.service.quartz;

import com.fh.mapper.OrderItemMapper;
import com.fh.mapper.OrdersMapper;
import com.fh.mapper.ProductSkuMapper;
import com.fh.model.OrderItem;
import com.fh.model.Orders;
import com.fh.model.ProductSku;
import com.fh.service.OrdersService;
import com.github.wxpay.sdk.WXPay;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class OrderTimeoutCheck {
  @Resource
  private OrdersMapper ordersMapper;
    @Resource
   private OrdersService ordersService;
    
    @Scheduled(cron = "0/3 * * * * ?")
    public void checkAndCloseOrder(){
        Example example = new Example(Orders.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("status","1");
        //当前时间的半个小时前
        Date time=new Date( System.currentTimeMillis()-30*60*1000);
        criteria.andLessThan("createTime",time);
        List<Orders> orders = ordersMapper.selectByExample(example);

     //访问微信平台接口 确定状态
     //如果支付了 状态改为2

    MyPayConfig config=new MyPayConfig();
        WXPay wxPay=new WXPay(config);
        try {
            for (Orders order : orders) {
                Map<String,String>  params=new HashMap<>();
                params.put("out_trade_no",order.getOrderId());
                Map<String, String> resp = wxPay.orderQuery(params);

                 if ("SUCCESS".equals(resp.get("trade_state"))){
                     Orders orders1=new Orders();
                     orders1.setOrderId(order.getOrderId());
                     orders1.setStatus("2");
                     ordersMapper.updateByPrimaryKeySelective(orders1);
                 }else if ("NOTPAY".equals(resp.get("trade_state"))){
                     Map<String, String> map = wxPay.orderQuery(params);
                  ordersService.closeOrder(order.getOrderId());

                 }


            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
